package com.asset.crm.client;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.asset.crm.domain.Employee;
import com.asset.crm.shared.ContactDTO;
import com.asset.crm.shared.EmployeeDTO;
import com.asset.crm.shared.InvoiceDTO;
import com.asset.crm.shared.ServiceItemDTO;
import com.asset.crm.shared.SkuDTO;
import com.asset.crm.shared.SkuItemDTO;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class sample implements EntryPoint {
  /**
   * The message displayed to the user when the server cannot be reached or
   * returns an error.
   */
  private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again.";

  /**
   * Create a remote service proxy to talk to the server-side Greeting service.
   */
  private final static GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

  private final Messages messages = GWT.create(Messages.class);
  
  private static String USER_NAME ;
  private  static String COMPANY;
  private  static String MESSAGE;
  private static EmployeeDTO employeeDTO;
  private static Boolean serviceFlag;
  private static Boolean productFlag;

  private static FlexTable flexTable = new FlexTable();
  private static FlexTable flexTable2 = new FlexTable();
  private static CheckBox SkuBox= new CheckBox();
  private static CheckBox serviceBox = new CheckBox();
  private static SkuDTO skuDTOp = null;
  private static int row=0;
  private static Label totalLabelValue  = new Label("00.00");
  /////SkuDTO
  
  private static ContactDTO  contactDTOp =new ContactDTO();
  private static HTMLPanel htmlPanel = new HTMLPanel("");
  
  /**
   * This is the entry point method.
   */
  private static class SearchDialog extends DialogBox{

	       HTML close = new HTML("[X]");
	       HTML title =new HTML("");
	       HorizontalPanel captionPanel = new HorizontalPanel();
	  public SearchDialog(boolean autoHide, boolean modal)
      {
        super(autoHide, modal);
        final Element td = getCellElement(0, 1);
        Element element =  (Element)td.getFirstChildElement();
       //DOM.removeChild(getContainerElement(), (com.google.gwt.user.client.Element) td);
        DOM.appendChild((com.google.gwt.user.client.Element) td, captionPanel.getElement());
        captionPanel.setStyleName("Caption");//width-100%
        captionPanel.add(title);
        close.addStyleName("CloseButton");//float:right
        captionPanel.add(close);
        super.setGlassEnabled(true);
        super.setAnimationEnabled(true);
        super.setWidth("1000");
        super.setHeight("1000");
      }
	  public SearchDialog(boolean autoHide){
	           this(autoHide, true);
	     }
      @Override
      public String getHTML()
       {
          return this.title.getHTML();
        }
      @Override
      public String getText()
        {
          return this.title.getText();
        }

      @Override
      public void setHTML(String html)
        {
          this.title.setHTML(html);
        }
      @Override
      public void setText(String text)
        {
          this.title.setText(text);
        }
      @Override
      protected void onPreviewNativeEvent(NativePreviewEvent event)
        {
          NativeEvent nativeEvent = event.getNativeEvent();

          if (!event.isCanceled()
            && (event.getTypeInt() == Event.ONCLICK)
            && isCloseEvent(nativeEvent))
            {
              this.hide();
            }
          super.onPreviewNativeEvent(event);
        }

      private boolean isCloseEvent(NativeEvent event)
        {
          return event.getEventTarget().equals(close.getElement());//compares equality of the underlying DOM elements
        }
	  public SearchDialog(String title){
		  this(false);
		  this.setTitle(title);
		  
		  setText("Search");
		  addCloseHandler(new CloseHandler<PopupPanel>() {
			
			@Override
			public void onClose(CloseEvent<PopupPanel> event) {
				// TODO Auto-generated method stub
				SearchDialog.this.hide(true);
				
			}
		});
	         // Enable animation.
	         setAnimationEnabled(true);
	         // Enable glass background.
	         setGlassEnabled(true);
	         // DialogBox is a SimplePanel, so you have to set its widget 
	         // property to whatever you want its contents to be.
	         Button ok = new Button("Login");
		  HorizontalPanel horizontalPanel = new HorizontalPanel();
		  Label label = new Label("Product Name");
		  final TextBox box = new TextBox();
		  Button  button = new Button("search");
		  button.setText("Search");
		  final VerticalPanel searchResultPanel =new VerticalPanel();
		  final Button choose = new Button();
		  if(this.getTitle().equalsIgnoreCase("sku")){
		  button.addClickHandler(new ClickHandler() {
			  
			@Override
			public void onClick(ClickEvent event) {
				searchResultPanel.clear();
				if(!box.getValue().trim().equalsIgnoreCase("")){
					
					greetingService.searchSkus(box.getValue(), new AsyncCallback<Set<SkuDTO>>() {
						
						@Override
						public void onSuccess(Set<SkuDTO> result) {
							if(result.size() > 0 ){
								//skuDTOs= result;
								for( final SkuDTO skuDTO :result){
									HorizontalPanel horizontalPanel= new HorizontalPanel();
									RadioButton radioButton =new RadioButton("skuName", skuDTO.getSkuName());
									Label codeLbl = new Label(skuDTO.getCode());
									radioButton.addClickHandler(new ClickHandler() {
										
										@Override
										public void onClick(ClickEvent event) {
											skuDTOp=skuDTO;
											choose.setEnabled(true);
											
										}
									});
									horizontalPanel.add(radioButton);
									horizontalPanel.add(codeLbl);
									searchResultPanel.add(horizontalPanel);
								}
							}else{
								Label label =new Label("No Results");
								searchResultPanel.add(label);
							}
							
						}
						
						@Override
						public void onFailure(Throwable caught) {
							caught.printStackTrace();
//							caught.p
							Window.alert("fail to search"+caught.getMessage());
						}
					});
				}
				
			}
		});
	  }else if(this.getTitle().equalsIgnoreCase("contact")){
		  button.addClickHandler(new ClickHandler() {
			  
				@Override
				public void onClick(ClickEvent event) {
					searchResultPanel.clear();
					if(!box.getValue().trim().equalsIgnoreCase("")){
						
						greetingService.searchContact(box.getValue(), new AsyncCallback<Set<ContactDTO>>() {
							
							@Override
							public void onSuccess(Set<ContactDTO> result) {
								if(result.size() > 0 ){
									//skuDTOs= result;
									for( final ContactDTO contactDTO :result){
										HorizontalPanel horizontalPanel= new HorizontalPanel();
										RadioButton radioButton =new RadioButton("contactName", contactDTO.getfName());
										Label codeLbl = new Label(contactDTO.getlName());
										radioButton.addClickHandler(new ClickHandler() {
											
											@Override
											public void onClick(ClickEvent event) {
												contactDTOp=contactDTO;
												choose.setEnabled(true);
												
											}
										});
										horizontalPanel.add(radioButton);
										horizontalPanel.add(codeLbl);
										searchResultPanel.add(horizontalPanel);
									}
								}else{
									Label label =new Label("No Results");
									searchResultPanel.add(label);
								}
								
							}
							
							@Override
							public void onFailure(Throwable caught) {
								caught.printStackTrace();
//								caught.p
								Window.alert("fail to search"+caught.getMessage());
							}
						});
					}
					
				}
			});
	  }
		  horizontalPanel.add(label);
		  horizontalPanel.add(box);
		  horizontalPanel.add(button);
		  choose.setText("choose");
		  choose.setEnabled(false);
		  if(this.getTitle().equalsIgnoreCase("sku")){
			  choose.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
//						Window.alert(skuDTOp.getSkuName());
//						Window.alert(row+"");
						
						TextBox textBox = (TextBox)flexTable.getWidget(row, 0);
						TextBox textBox2 = (TextBox)flexTable.getWidget(row, 1);
						TextBox textBox3 = (TextBox)flexTable.getWidget(row, 3);
						TextBox discountTxt = (TextBox)flexTable.getWidget(row, 2);
						TextBox quantityTxt = (TextBox)flexTable.getWidget(row, 4);
						TextBox totalTxt = (TextBox)flexTable.getWidget(row, 7);
						textBox.setValue(skuDTOp.getSkuName());
						textBox2.setValue(skuDTOp.getCode());
						textBox3.setValue(skuDTOp.getPrice());
						discountTxt.setValue("0");
						quantityTxt.setValue("0");
						totalTxt.setText("00.00");
						SearchDialog.this.hide(true);
						
					}
				});  
		  }else if(this.getTitle().equalsIgnoreCase("contact")){
			  choose.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						  TextBox textBox =  (TextBox)htmlPanel.getWidget(1);
						  textBox.setValue(contactDTOp.getfName());
						  SearchDialog.this.hide(true);
						
					}
				});  
			 
		  }
		
		  VerticalPanel root = new VerticalPanel();
		  
		  root.add(horizontalPanel);
		  root.add(searchResultPanel);
		  root.add(choose);
		  setWidget(root);
	  }
  }
  private static class invoiceDialog extends DialogBox{
	  public invoiceDialog(){
		  final Label errorLbl = new Label("");
		  Button button = new Button();
		  button.setText("OK");
		  setText("select Invoice");
		  setAnimationEnabled(true);
		  setGlassEnabled(true);
		  VerticalPanel verticalPanel = new VerticalPanel();
		  Label emailLbl = new Label("Select Invoice Type");
//		  ListBox listBox =new ListBox();
//		  listBox.addItem("Service", "service");
//		  listBox.addItem("Product", "product");
		  HorizontalPanel servicePanel= new HorizontalPanel();
		  Label serviceLbl = new Label("Service");
		  Label productLbl = new Label("Product");
		  final CheckBox  serviceCh = new CheckBox();
		  serviceCh.setValue(false);
		  final CheckBox  productCh = new CheckBox() ;
		  productCh.setValue(false);
		  flexTable.setVisible(false);
		  flexTable2.setVisible(false);
		  serviceCh.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(serviceCh.getValue()){
					serviceBox.setValue(true);
					flexTable2.setVisible(true);
				}else{
					serviceBox.setValue(false);
					flexTable2.setVisible(false);
				}
				
			}
		});
		  productCh.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(productCh.getValue()){
					SkuBox.setValue(true);
					flexTable.setVisible(true);
				}else{
					SkuBox.setValue(false);
					flexTable.setVisible(false);
				}
			}
		});
		  		  servicePanel.add(serviceCh);
		  servicePanel.add(serviceLbl);
		  HorizontalPanel productPanel = new HorizontalPanel();
		  productPanel.add(productCh);
		  productPanel.add(productLbl);
		  verticalPanel.add(productPanel);
		  String width =  Window.getClientWidth()/2+"";
		  String height = Window.getClientHeight()/2+"";
		  this.setWidth(width);
		  this.setHeight(height);
		  this.center();
		  verticalPanel.add(emailLbl);
		  verticalPanel.add(servicePanel);
		  verticalPanel.add(productPanel);
		  verticalPanel.add(errorLbl);
		  button.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				if(productCh != null && serviceCh != null){
					if(!(productCh.getValue()|| serviceCh.getValue())){
						errorLbl.setText("please choose invoice type");
					}else{
						errorLbl.setText("");
						invoiceDialog.this.hide();
					}
				}

			}
		});
		  verticalPanel.add(button);
		  setWidget(verticalPanel);
	  }
  }
  private static class MyDialog extends DialogBox {

      public MyDialog() {
         //spanElement.setInnerHTML(MESSAGE);
         setText("Quick Login");
         // Enable animation.
         setAnimationEnabled(true);
         // Enable glass background.
         setGlassEnabled(true);
         // DialogBox is a SimplePanel, so you have to set its widget 
         // property to whatever you want its contents to be.
         Button ok = new Button("Login");
         
         Label emailLbl = new Label("E-mail");
         Label  passwordLbl = new Label("Password");
         final TextBox emailTxt = new TextBox();
         final TextBox passwordTxt = new TextBox();
         Label comapnyLbl = new Label("Company");
         final TextBox companyTxt = new TextBox();

         VerticalPanel panel = new VerticalPanel();
         panel.setHeight("500");
         panel.setWidth("500");
         panel.setSpacing(10);
         panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
         panel.add(emailLbl);
         panel.add(emailTxt);
         panel.add(passwordLbl);
         panel.add(passwordTxt);
         panel.add(comapnyLbl);
         panel.add(companyTxt);
         final Label errorLbl = new Label("");
         errorLbl.setVisible(false);
         panel.add(errorLbl);
         panel.add(ok);
         ok.addClickHandler(new ClickHandler() {
             public void onClick(ClickEvent event) {
            	// USER_NAME = emailTxt.getText().trim();
            	 if(emailTxt.getText().trim() != null && passwordTxt.getText().trim() != null ){
            		 greetingService.login(emailTxt.getText().trim(), passwordTxt.getText(), companyTxt.getText(), new AsyncCallback<EmployeeDTO>() {
            			 
						
						@Override
						public void onSuccess(EmployeeDTO result) {
							if(result != null){
								employeeDTO = result;
								USER_NAME =  result.getEmail();
								COMPANY = companyTxt.getText();
								MyDialog.this.hide();
								invoiceDialog dialog = new invoiceDialog();
								dialog.show();
								 
							}
							else{
//								new MyDialog();
								errorLbl.setText("error user name or password or company");
								errorLbl.setVisible(true);
							}
							
						}
						
						@Override
						public void onFailure(Throwable caught) {
							errorLbl.setText("error user name or password or company");
							errorLbl.setVisible(true);
						}

					});
            	 }else{
            		 
            	 }
                //MyDialog.this.hide();
             }
          });

         setWidget(panel);
      }
   }
     public void onModuleLoad() {    	 
   
   HorizontalPanel  servicePanel =  new HorizontalPanel();
   HorizontalPanel  productPanel =  new HorizontalPanel();
   Label  contactLbl =new Label("contact");
   TextBox contactTxt = new TextBox();
   contactTxt.setTitle("contact");
   contactTxt.addClickHandler(new ClickHandler() {
	
	@Override
	public void onClick(ClickEvent event) {
		SearchDialog searchDialog = new SearchDialog("contact");
		searchDialog.setPopupPosition(500, 500);
		searchDialog.show();
		
	}
});
   Label  invoiceLbl =new Label("Invoice Number");
   TextBox invoiceTxt = new TextBox();
   htmlPanel.add(contactLbl);
   htmlPanel.add(contactTxt);
   htmlPanel.add(invoiceLbl);
   htmlPanel.add(invoiceTxt);
   
   SkuBox.setStylePrimaryName("gwtCheckBox");
   //SkuBox.setChecked(true);
   serviceBox.setStylePrimaryName("gwtCheckBox");
   //serviceBox.setChecked(true);
   Label  serviceLbl =new Label("Service Invoice");
   Label  skuLbl =new Label("Product Invoice");
   Button serviceAddRow=new Button();
   serviceAddRow.setText("Add Service");
   serviceAddRow.addClickHandler(new  ClickHandler() {
	@Override
	public void onClick(ClickEvent event) {
		int i= flexTable2.getRowCount();
		for(int j=0 ;j<=7;j++){
		  if(j == 5 || j == 6){
			  ListBox listBox = new ListBox();
			  listBox.addItem("none", "0");
			  listBox.addItem("tax1", "10");
			  listBox.addItem("tax2", "20");
			  listBox.addChangeHandler(new ChangeHandler() {
				
				@Override
				public void onChange(ChangeEvent event) {
					//Window.alert("onChange");
					Double double1 = updateLineTotal(row, flexTable2);
					TextBox textBox = (TextBox)flexTable2.getWidget(row, 7);
					textBox.setValue(double1.toString());
					//Window.alert("onChange"+double1);
					Double double2 =getTotal(sample.flexTable2, sample.flexTable2);
					totalLabelValue.setText(double2.toString());
				}
			});
			  listBox.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					// TODO Auto-generated method stub
					Cell cell =flexTable2.getCellForEvent(event);
					row = cell.getRowIndex();
				}
			});
			  flexTable2.setWidget(i, j, listBox);
		  }else{
			  TextBox  textBox = new TextBox();
			  if(j == 0 && flexTable2.getTitle().equalsIgnoreCase("product")){
				  textBox.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						SearchDialog searchDialog = new SearchDialog("sku");
						searchDialog.setPopupPosition(500, 500);
						searchDialog.show();
//						 textBox = event.getRelativeElement().getParentElement().getNodeName();
//						textBox.getParentElement().getNodeName();
						Cell cell =flexTable2.getCellForEvent(event);
						//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
						row = cell.getRowIndex();
					}
				});
			  }else if (j == 2 ||j==3||j==4) {
				  if(j==2){
					  textBox.setValue("00");
					  
				  }else if(j==3){
					  textBox.setValue("00.00");
					  
				  }else if(j==4){
					  textBox.setValue("00");
				  }
				textBox.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						Cell cell =flexTable2.getCellForEvent(event);
						//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
						row = cell.getRowIndex();
						
					}
				});
				textBox.addBlurHandler(new BlurHandler() {
					
					@Override
					public void onBlur(BlurEvent event) {
						Double double1 = updateLineTotal(row, flexTable2);
						TextBox textBox = (TextBox)flexTable2.getWidget(row, 7);
						textBox.setValue(double1.toString());
						Double double2 =getTotal(sample.flexTable2, sample.flexTable2);
						totalLabelValue.setText(double2.toString());
						
					}
				});
			}else if(j==7){
				textBox.setValue("00.00");
				textBox.addValueChangeHandler(new ValueChangeHandler<String>() {
					
					@Override
					public void onValueChange(ValueChangeEvent<String> event) {
						//Window.alert("value change");
						
					}
				});
			}
			  flexTable2.setWidget(i, j,textBox );
		  }
  	  	
		}
	}
}); 
   servicePanel.add(serviceAddRow);
   serviceLbl.setStylePrimaryName("gwtCheckBoxLbl");
   skuLbl.setStylePrimaryName("gwtCheckBoxLbl");
   serviceBox.addClickHandler(new ClickHandler() {
	
	@Override
	public void onClick(ClickEvent event) {
		if(serviceBox.getValue()){
			getFlexTableService(flexTable2);
			flexTable2.setVisible(true);
		}
		else{
			flexTable2.setVisible(false);
		}
		
	}
});
   SkuBox.addClickHandler(new ClickHandler() {
	
	@Override
	public void onClick(ClickEvent event) {
		if(SkuBox.getValue()){
			getFlexTableProduct(flexTable);
			flexTable.setVisible(true);
		}else{
			flexTable.setVisible(false);
		}
		
	}
});
   Button addProductbtn = new Button();
   addProductbtn.setText("Add Product");
   addProductbtn.addClickHandler(new ClickHandler() {
	
	@Override
	public void onClick(ClickEvent event) {
		
		int i= flexTable.getRowCount();
		for(int j=0 ;j<=7;j++){
		  if(j == 5 || j == 6){
			  ListBox listBox = new ListBox();
			  listBox.addItem("none", "0");
			  listBox.addItem("tax1", "1");
			  listBox.addItem("tax2", "2");
			  listBox.addChangeHandler(new ChangeHandler() {
				
				@Override
				public void onChange(ChangeEvent event) {
					//Window.alert("onChange");
					Double double1 = updateLineTotal(row, flexTable);
					TextBox textBox = (TextBox)flexTable.getWidget(row, 7);
					textBox.setValue(double1.toString());
					//Window.alert("onChange"+double1);
					Double double2 =getTotal(sample.flexTable, sample.flexTable2);
					totalLabelValue.setText(double2.toString());
				}
			});
			  listBox.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					// TODO Auto-generated method stub
					Cell cell =flexTable.getCellForEvent(event);
					row = cell.getRowIndex();
				}
			});
			  flexTable.setWidget(i, j, listBox);
		  }else{
			  TextBox  textBox = new TextBox();
			  if(j == 0 && flexTable.getTitle().equalsIgnoreCase("product")){
				  textBox.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						SearchDialog searchDialog = new SearchDialog("sku");
						searchDialog.setPopupPosition(500, 500);
						searchDialog.show();
//						 textBox = event.getRelativeElement().getParentElement().getNodeName();
//						textBox.getParentElement().getNodeName();
						Cell cell =flexTable.getCellForEvent(event);
						//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
						row = cell.getRowIndex();
					}
				});
			  }else if (j == 2 ||j==3||j==4) {
				  if(j==2){
					  textBox.setValue("00");
					  
				  }else if(j==3){
					  textBox.setValue("00.00");
					  
				  }else if(j==4){
					  textBox.setValue("00");
				  }
				textBox.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						Cell cell =flexTable.getCellForEvent(event);
						//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
						row = cell.getRowIndex();
						
					}
				});
				textBox.addBlurHandler(new BlurHandler() {
					
					@Override
					public void onBlur(BlurEvent event) {
						Double double1 = updateLineTotal(row, flexTable);
						TextBox textBox = (TextBox)flexTable.getWidget(row, 7);
						textBox.setValue(double1.toString());
						Double double2 =getTotal(sample.flexTable, sample.flexTable2);
						totalLabelValue.setText(double2.toString());
						
					}
				});
			}else if(j==7){
				textBox.setValue("00.00");
				textBox.addValueChangeHandler(new ValueChangeHandler<String>() {
					
					@Override
					public void onValueChange(ValueChangeEvent<String> event) {
						//Window.alert("value change");
						
					}
				});
			}
			  flexTable.setWidget(i, j,textBox );
		  }
  	  	
		}
	
		
	}
});
   servicePanel.add(serviceBox);
   
   servicePanel.add(serviceLbl);
   productPanel.add(SkuBox);
   productPanel.add(skuLbl);
   productPanel.add(addProductbtn);
   htmlPanel.add(servicePanel);
   htmlPanel.add(productPanel);
    flexTable.setTitle("product");
	flexTable= getFlexTableProduct(flexTable);
	
	flexTable2.setTitle("Service");
	flexTable2 = getFlexTableService(flexTable2);
	htmlPanel.add(flexTable);
	htmlPanel.add(flexTable2);
	MyDialog myDialog = new MyDialog();

    int left = Window.getClientWidth()/ 2;
    int top = Window.getClientHeight()/ 2;
    myDialog.setPopupPosition(left, top);

    htmlPanel.add(myDialog);
    HorizontalPanel totalPanel =new HorizontalPanel();
    HorizontalPanel discountPanel =new HorizontalPanel();
    HorizontalPanel totalwithdisPanel =new HorizontalPanel();
    Label totalLabel = new Label("Invoice Total");
    //Label totalLabelValue  = new Label();
    totalLabelValue.setStylePrimaryName("totalTd");
    totalLabel.setStylePrimaryName("totalTd");
    totalPanel.add(totalLabel);
    totalPanel.add(totalLabelValue);
    ////////////////////////////////////////////////
    Label discountLbl =new Label("Discount");
    TextBox discountTxt= new TextBox();
    discountLbl.setStylePrimaryName("totalTd");
    discountTxt.setStylePrimaryName("totalTd");
    discountPanel.add(discountLbl);
    discountPanel.add(discountTxt);
    //////////////////////////////////////
    Label DisTotalLbl = new Label("After Discount ");
    Label DisTotalLblValue  = new Label();
    DisTotalLbl.setStylePrimaryName("totalTd");
    DisTotalLblValue.setStylePrimaryName("totalTd");
    totalwithdisPanel.add(DisTotalLbl);
    totalwithdisPanel.add(DisTotalLblValue);
    ///////////////////////////////////////////
    VerticalPanel verticalPanel = new VerticalPanel();
    verticalPanel.add(totalPanel);
    verticalPanel.add(discountPanel);
    verticalPanel.add(totalwithdisPanel);
    verticalPanel.setStylePrimaryName("totalTable");
    htmlPanel.add(verticalPanel);
    Button save = new Button();
    save.setText("save");
    Button cancel = new Button();
    save.setText("save");
    cancel.setText("cancel");
    cancel.addClickHandler(new ClickHandler() {
		
		@Override
		public void onClick(ClickEvent event) {
			// TODO Auto-generated method stub
			Window.alert("hi");
			SearchDialog searchDialog = new SearchDialog(false,true);
			searchDialog.show();
		}
	});
    save.addClickHandler(new SaveHandler());
    htmlPanel.add(save);
    htmlPanel.add(cancel);
    RootPanel.get("flextable").add(htmlPanel);
    myDialog.show();
    
//
//      /**
//       * Send the name from the nameField to the server and wait for a response.
//       */
     }
     
      private void renderFlexTableHeader(FlexTable flexTable, String type,String infoCode,String costUnit,String quantityHour ) {
  	    flexTable.setWidget(0, 0, new Label(type));
  		flexTable.setWidget(0, 1, new Label(infoCode));
  		flexTable.setWidget(0, 2, new Label("Discount %"));
  		flexTable.setWidget(0, 3, new Label(costUnit));
  		flexTable.setWidget(0, 4, new Label(quantityHour));
  		flexTable.setWidget(0, 5, new Label("Tax"));
  		flexTable.setWidget(0, 6, new Label("Tax"));
  		flexTable.setWidget(0, 7, new Label("Line Total"));
	}
      private static FlexTable renderFlexTableRow(final FlexTable flexTable ,Integer rowCount, Integer colCount) {

    	  for (int i = 1; i <= rowCount; i++) {
    		  for (int j = 0; j < colCount; j++) {
    			  if(j == 5 || j == 6){
    				  ListBox listBox = new ListBox();
    				  listBox.addItem("none", "0");
    				  listBox.addItem("tax1", "10");
    				  listBox.addItem("tax2", "20");
    				  listBox.addChangeHandler(new ChangeHandler() {
						
						@Override
						public void onChange(ChangeEvent event) {
							//Window.alert("onChange");
							Double double1 = updateLineTotal(row, flexTable);
							TextBox textBox = (TextBox)flexTable.getWidget(row, 7);
							textBox.setValue(double1.toString());
							//Window.alert("onChange"+double1);
							Double double2 =getTotal(sample.flexTable, sample.flexTable2);
							totalLabelValue.setText(double2.toString());
						}
					});
    				  listBox.addClickHandler(new ClickHandler() {
						
						@Override
						public void onClick(ClickEvent event) {
							// TODO Auto-generated method stub
							Cell cell =flexTable.getCellForEvent(event);
							row = cell.getRowIndex();
						}
					});
    				  flexTable.setWidget(i, j, listBox);
    			  }
    			  else{
    				  TextBox  textBox = new TextBox();
    				  if(j == 0 && flexTable.getTitle().equalsIgnoreCase("product")){
        				 // Label label = new Label();
    					  textBox.setTitle("searchSkus");
    					  textBox.addClickHandler(new ClickHandler() {
    						
    						@Override
    						public void onClick(ClickEvent event) {
    							SearchDialog searchDialog = new SearchDialog("sku");
    							searchDialog.setPopupPosition(500, 500);
    							searchDialog.show();
//    							 textBox = event.getRelativeElement().getParentElement().getNodeName();
//    							textBox.getParentElement().getNodeName();
    							Cell cell =flexTable.getCellForEvent(event);
    							//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
    							row = cell.getRowIndex();
    						}
    					});
    				  }
    				  if(j==1&& flexTable.getTitle().equalsIgnoreCase("product")){
    					  textBox.setEnabled(false);
    				  }
    				  else if (j == 2 ||j==3||j==4) {
    					  if(j==2){
    						  textBox.setValue("00");
    						  textBox.addKeyPressHandler(new NumberHandler());
    						  
    					  }else if(j==3){
    						  textBox.setValue("00.00");
    						  textBox.addKeyPressHandler(new NumberHandler());
    						  
    					  }else if(j==4){
    						  textBox.setValue("00");
    						  textBox.addKeyPressHandler(new NumberHandler());
    					  }
						textBox.addClickHandler(new ClickHandler() {
							
							@Override
							public void onClick(ClickEvent event) {
								Cell cell =flexTable.getCellForEvent(event);
								//Window.alert(cell.getRowIndex()+" "+cell.getRowIndex());
								row = cell.getRowIndex();
								
							}
						});
						textBox.addBlurHandler(new BlurHandler() {
							
							@Override
							public void onBlur(BlurEvent event) {
								Double double1 = updateLineTotal(row, flexTable);
								TextBox textBox = (TextBox)flexTable.getWidget(row, 7);
								textBox.setValue(double1.toString());
								Double double2 =getTotal(sample.flexTable, sample.flexTable2);
								totalLabelValue.setText(double2.toString());
								
							}
						});
					}else if(j==7){
						textBox.setValue("00.00");
						textBox.addValueChangeHandler(new ValueChangeHandler<String>() {
							
							@Override
							public void onValueChange(ValueChangeEvent<String> event) {
								//Window.alert("value change");
								
							}
						});
					}
    				  flexTable.setWidget(i, j,textBox );
    			  }
    	    	  	
			}
		}
    	  return flexTable;
	}
      
     FlexTable getFlexTableProduct(FlexTable flexTable){
    	   flexTable.setCellSpacing(0);
    	   flexTable.setCellPadding(0);
    	   flexTable.setStylePrimaryName("invoiceTable");
//    		flexTable.setBorderWidth(width)
    	   renderFlexTableHeader(flexTable,"Product","Code","Unit Price","Quantity");
    	  flexTable = renderFlexTableRow(flexTable,3, 8);
    		return flexTable;
     }
     FlexTable getFlexTableService(FlexTable flexTable){
	   flexTable.setCellSpacing(0);
  	   flexTable.setCellPadding(0);
  	   flexTable.setStylePrimaryName("invoiceTable");
  	   renderFlexTableHeader(flexTable,"Service","Info","Cost Per Hour","Hours");
	   flexTable = renderFlexTableRow(flexTable,3, 8);
		return flexTable;
     }
     
     private static class SaveHandler implements ClickHandler{
    	 private List<String> validateHandler(){
    		 TextBox contactTextBox	= (TextBox)htmlPanel.getWidget(1);
 			 TextBox invoceNumberTextBox	= (TextBox)htmlPanel.getWidget(3);
 			 ValidateSampleModule.messageProxy(contactTextBox.getValue(),"contact");
 			ValidateSampleModule.messageProxy(invoceNumberTextBox.getValue(),"invoice");
 			 return ValidateSampleModule.errors;
 			
    	 }
		@Override
		public void onClick(ClickEvent event) {
			List<String>  strings = validateHandler();
			if(strings != null && strings.size()>0){
			TextBox contactTextBox	= (TextBox)htmlPanel.getWidget(1);
			TextBox invoceNumberTextBox	= (TextBox)htmlPanel.getWidget(3);
			InvoiceDTO invoiceDTO =new InvoiceDTO();
			invoiceDTO.setContact(contactDTOp.getId());
			invoiceDTO.setCode(invoceNumberTextBox.getValue());
			invoiceDTO.setOwner(USER_NAME);
			invoiceDTO.setTotalPrice(totalLabelValue.getText());
			//List<E>
			if(SkuBox.getValue()){
				List<SkuItemDTO>skuItemDTOs = new ArrayList<SkuItemDTO>(); 
				for(int i = 1; i< flexTable.getRowCount();i++){
					SkuItemDTO skuItemDTO = new SkuItemDTO();
				TextBox box = (TextBox)flexTable.getWidget(i, 0);
				if(box.getValue()!= null && !box.getValue().equalsIgnoreCase("")){
					for(int j = 0 ;j<=7;j++){
						if(j == 5){
							ListBox listBox =(ListBox)flexTable.getWidget(i, j);
							skuItemDTO.setTaxOne(new Integer(listBox.getSelectedIndex()).toString());
						}else if(j==6){
							ListBox listBox =(ListBox)flexTable.getWidget(i, j);
							skuItemDTO.setTaxTwo(new Integer(listBox.getSelectedIndex()).toString());
						}else if (j==0) {
							TextBox textBox = (TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setName(textBox.getName());
						}else if (j== 1) {
							TextBox  textBox =(TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setCode(textBox.getValue());
						}else if (j==2) {
							TextBox textBox = (TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setDiscount(textBox.getValue());
						}else if (j== 3) {
							TextBox  textBox = (TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setPrice(textBox.getValue());
						}else if (j== 4) {
							TextBox textBox =(TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setQuantity(textBox.getValue());
						}else if(j==7){
							TextBox textBox = (TextBox)flexTable.getWidget(i, j);
							skuItemDTO.setTotalPrice(textBox.getValue());
						}
					}
				}
					skuItemDTOs.add(skuItemDTO);
				}
				invoiceDTO.setSkuItemDTOs(skuItemDTOs);
			}
			if(serviceBox.getValue()){
				List<ServiceItemDTO> serviceItemDTOs =new ArrayList<ServiceItemDTO>();
				for(int i = 1; i< flexTable2.getRowCount();i++){
					ServiceItemDTO serviceItemDTO = new ServiceItemDTO();
					TextBox box = (TextBox)flexTable.getWidget(i, 0);
					if(box.getValue()!= null && !box.getValue().equalsIgnoreCase("")){
						for(int j =0;j <= 7 ;j++ ){
							if(j == 5){
								ListBox listBox =(ListBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setTaxOne(new Integer(listBox.getSelectedIndex()).toString());
							}else if(j==6){
								ListBox listBox =(ListBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setTaxTwo(new Integer(listBox.getSelectedIndex()).toString());
							}else if (j==0) {
								TextBox textBox = (TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setName(textBox.getName());
							}else if (j== 1) {
								TextBox  textBox =(TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setCode(textBox.getValue());
							}else if (j==2) {
								TextBox textBox = (TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setDiscount(textBox.getValue());
							}else if (j== 3) {
								TextBox  textBox = (TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setCostPerHour(textBox.getValue());
							}else if (j== 4) {
								TextBox textBox =(TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setHours(textBox.getValue());
							}else if(j==7){
								TextBox textBox = (TextBox)flexTable2.getWidget(i, j);
								serviceItemDTO.setTotalCost(textBox.getValue());
							}
						}
					}
					serviceItemDTOs.add(serviceItemDTO);
				}
				invoiceDTO.setServiceItemDTOs(serviceItemDTOs);
			}
			greetingService.saveInvoice(invoiceDTO, new AsyncCallback<Void>() {
				
				@Override
				public void onSuccess(Void result) {
					Window.alert("sales");
					redirect("http://localhost:8080/sales");
					
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					Window.alert("saved fail");
					
				}
			});
		}
			else{
				Window.alert("error in data");
			}
	}
    	 
     }
     private static class NumberHandler implements KeyPressHandler{

		@Override
		public void onKeyPress(KeyPressEvent event) {
			TextBox input = (TextBox)event.getSource();
			
	        if (!input.getValue().matches("[0-9]*")) {
	            Window.alert("please enter numbers only");
	            
	        }
			
		}
    	 
     }
     private static Double updateLineTotal(int row,FlexTable flexTable){
    	 TextBox discount =(TextBox)flexTable.getWidget(row, 2);
    	 TextBox unitPrice =(TextBox)flexTable.getWidget(row, 3);
    	 TextBox quantity=(TextBox)flexTable.getWidget(row, 4);
    	 ListBox listBox1 =(ListBox)flexTable.getWidget(row, 5);
    	 ListBox listBox2 =(ListBox)flexTable.getWidget(row, 6);
    	 Double total = getLineTotal( discount.getValue(), unitPrice.getValue(), quantity.getValue(), listBox1.getValue(listBox1.getSelectedIndex()), listBox2.getValue(listBox2.getSelectedIndex()));
    	 return total;
     }
     private static Double getLineTotal(String discount,String unitPrice,String quantity,String tax1,String tax2){
    	 Double totalLine= new Double(0.0);
    	 Double discountD = Double.parseDouble(discount);
    	 Double unitPriceD = Double.parseDouble(unitPrice);
    	 Double quantityD = Double.parseDouble(quantity);
    	 Double tax1D = Double.parseDouble(tax1);
    	 Double tax2D = Double.parseDouble(tax2);
    	 totalLine = (quantityD*unitPriceD)-(quantityD*unitPriceD*discountD/100)+tax1D+tax2D;
    	 return totalLine;
    	 
     }
     private static Double getTotal(FlexTable flexTable,FlexTable flexTable2){
    	 Double total = new Double(0.0);
    	 if(flexTable != null){
    		 int rowCount= flexTable.getRowCount();
   
    		 for(int i = 1 ;i<rowCount;i++){
    			 total += Double.parseDouble(((TextBox)(flexTable.getWidget(i, 7))).getValue());
    		 }
    	 }
    	 if(flexTable2 != null){
    		 int rowCount= flexTable2.getRowCount();
    		 for(int i = 1 ;i<rowCount;i++){
    			 total += Double.parseDouble(((TextBox)(flexTable2.getWidget(i, 7))).getValue());
    		 }
    	 }
    	 return total;
     }
     native static void redirect(String url) 
     /*-{ 
             $wnd.location.replace(url); 
     }-*/;
}
